var SkywriterLoader = function() {
	return {
		init: function(field, panel, syntax) {
    		bespin.useBespin(field).then(function(environment){
				var editor = environment.editor;
				editor.syntax = syntax;
				editor.textChanged = function(){ Ext.getCmp(panel).markDirty(); }

				MODx.onSaveEditor = function(fld) {
					fld.setValue(editor.value);
				};

			}, function(error) {
				throw new Error("Launch failed: " + error);
			});

			return true;
		},

		OnRichTextEditorInit: function() {
			return SkywriterLoader.init('ta', 'modx-panel-resource', 'html');
		},

		OnRichTextBrowserInit: function() {
			return SkywriterLoader.init('ta', 'modx-panel-resource', 'html');
		},

		OnChunkFormPrerender: function() {
			return SkywriterLoader.init('modx-chunk-snippet', 'modx-panel-chunk', 'html');
		},

		OnPluginFormPrerender: function() {
			return SkywriterLoader.init('modx-plugin-plugincode', 'modx-panel-plugin', 'php');
		},

		OnSnipFormPrerender: function() {
			return SkywriterLoader.init('modx-snippet-snippet', 'modx-panel-snippet', 'php');
		},

		OnTempFormPrerender: function() {
			return SkywriterLoader.init('modx-template-content', 'modx-panel-template', 'html');
		}
	};
}();

Ext.onReady(function() {
	MODx.onLoadEditor = SkywriterLoader[MODx.skywriter.event];
	MODx.onLoadEditor();
});